package com.woohua.thread.limite;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/***
 * @title CurrentLimitAspect
 * @description:拦截器，在controller执行前后拦截
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/14 8:54
 **/
@Aspect
@Component
public class CurrentLimitAspect {

    /**
     * 拦截controller, 自行修改路径
     */
    @Pointcut("execution(* com.woohua.thread..*(..))")
    public void controller() {

    }

    @Before("controller()")
    public void controller(JoinPoint point) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取通行证， urlPath的格式如： /limit
        CurrentLimiter.tryAcquire(request.getRequestURI());
    }

    /**
     * controller 执行完后调用，即使controller 抛出异常这个拦截方法也会被调用
     *
     * @param point
     */
    @After("controller()")
    public void after(JoinPoint point) {
        // 释放获取到的通行证
        CurrentLimiter.release();
    }

}
